﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Lichtspiel.ECSystem
{
    public class Node<T> : IUpdateable, IRenderable where T : IRenderable, IUpdateable
    {
        private List<ChildData> children = new List<ChildData>();
        private int added = 0; // counter for sorting nodes by add-'time'
        private DepthComparer comparer = new DepthComparer();

        public void AddChild(T child) {
            AddChild(child, 0);
        }

        public void AddChild(T child, int z) {
            this.children.Add(new ChildData(child, z, added));
            added++;
            this.children.Sort(comparer);
        }

        public virtual void Update(GameTime time) {
            for (int i = children.Count - 1; i >= 0; i--) {
                children[i].Data.Update(time);
            }
        }

        public virtual void Render() {
            for (int i = 0; i < children.Count; i++) {
                children[i].Data.Render();
            }
        }

        public IEnumerator<T> GetEnumerator() {
            for (int i = children.Count - 1; i >= 0; i--) {
                yield return children[i].Data;
            }
        }

        private class ChildData
        {
            public readonly T Data;
            public readonly int Z;
            public readonly int Added;
            public ChildData(T data, int z, int added) {
                this.Data = data;
                this.Z = z;
                this.Added = added;
            }
        }

        private class DepthComparer : IComparer<ChildData>
        {
            public int Compare(ChildData a, ChildData b) {
                if (a.Z > b.Z)
                    return 1;
                if (a.Z < b.Z)
                    return -1;

                if (a.Added > b.Added)
                    return 1;
                if (a.Added < b.Added)
                    return -1;

                return 0;
            }
        }
    }
}
